package com.hlingsoft.cms.action.manage;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;
import com.hlingsoft.cms.dao.CommentDao;
import com.hlingsoft.cms.dao.ImageDao;
import com.hlingsoft.cms.dao.LikesDao;
import com.hlingsoft.cms.dao.NewsDao;
import com.hlingsoft.cms.entity.*;
import com.hlingsoft.cms.entity.vo.JsonVo;
import com.hlingsoft.cms.entity.vo.NewsManageVo;
import com.hlingsoft.cms.entity.vo.NewsVo;
import com.hlingsoft.cms.entity.vo.PageVo;
import com.hlingsoft.cms.util.Common;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* Created by selbylei on 2015/6/7.
*/

@Controller
@RequestMapping("/manage/news")
public class ManageNewsAction extends ManageBaseAction {

    @Autowired
    private NewsDao newsDao;

    @Autowired
    private ImageDao imageDao;

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private LikesDao likesDao;



    @RequestMapping(value = "/list.htm", method = RequestMethod.GET)
    public String index(
            @RequestParam(value = "p", defaultValue = "1") int pageNum,
            ModelMap modelMap) {
        PageVo<NewsManageVo> pageVo = new PageVo<NewsManageVo>(pageNum);
        pageVo.setRows(10);
        pageVo.basePath = "/manage/news/list.htm";

        List<News> newsList = newsDao.getNewsByAppUserId(1);
        List<NewsManageVo> newsManageVoList = new ArrayList<NewsManageVo>();
        for (News news:newsList){
            NewsManageVo newsManageVo = new NewsManageVo();
            newsManageVo.setAppUserId(news.getAppUserId());
            newsManageVo.setCreateTime(news.getCreateTime());
            newsManageVo.setUpdateTime(news.getUpdateTime());
            newsManageVo.setContent(news.getContent());
            newsManageVo.setId(news.getId());

            List<Image> image = imageDao.getImageByNewsId(news.getId());
            newsManageVo.setImage(image.get(0).getPath());
            newsManageVo.setAuthorization(news.getAuthorization());

            newsManageVoList.add(newsManageVo);
        }

        pageVo.setList(newsManageVoList);
        pageVo.setCount(newsManageVoList.size());
        modelMap.put("p", pageNum);
        modelMap.put("pageVo", pageVo);

        return "manage/news/list";
    }



    @RequestMapping(value = "/add.htm", method = RequestMethod.GET)
    public String add(ModelMap modelMap) {

        return "manage/news/add";
    }


    /**
     * 添加系统动态
     * @param content
     * @param file
     * @param request
     * @param modelMap
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/add.json")
    public JsonVo<String> add(
            @RequestParam(value = "content") String content,
            @RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest request, ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();
        try {

            Date now = new Date();
            News news = new News();
            news.setAppUserId(1);
            news.setContent(content);
            news.setCreateTime(now);
            news.setUpdateTime(now);
            newsDao.addNews(news);

            if (file!=null) {
                String fileName = file.getOriginalFilename();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleFormat.format(new Date());
                putObject(dateString, fileName, file.getInputStream(),
                        file.getSize());
                String path = "http://icake.oss-cn-hangzhou.aliyuncs.com/news/" + dateString + "/" + fileName;

                CommonsMultipartFile cf= (CommonsMultipartFile)file;
                DiskFileItem fi = (DiskFileItem)cf.getFileItem();
                File f = fi.getStoreLocation();
                BufferedImage sourceImg = ImageIO.read(new FileInputStream(f));

                Image image = new Image();
                image.setAppUserId(1);
                image.setHeight(sourceImg.getHeight());
                image.setWidth(sourceImg.getWidth());
                image.setPath(path);
                image.setType(2);
                image.setCreateTime(now);
                image.setTokeTime(now);
                image.setUpdateTime(now);
                image.setNewsId(news.getId());
                imageDao.addImages(image);
            }

            json.setResult(true);
            return json;
        } catch (IOException e) {
            e.printStackTrace();
            json.setResult(false);
            return json;
        }
    }


    @RequestMapping(value = "/delete.json")
    @ResponseBody
    public JsonVo<String> delete(@RequestParam(value = "newsId") long newsId,
                                 ModelMap modelMap) {
        JsonVo<String> json = new JsonVo<String>();

        //删除相关图片
        List<Image> imageList = imageDao.getImageByNewsId(newsId);
        for (Image image:imageList){
            imageDao.deleteImage(image.getId());
        }

        //删除相关评论
        List<Comment> commentList=commentDao.getCommentByNewsId2(newsId);
        for (Comment comment:commentList){
            commentDao.getCommentByNewsId(comment.getId());
        }

        //删除相关点赞
        List<Likes> likesList = likesDao.getLikesByNewsId2(newsId);
        for (Likes likes:likesList){
            likesDao.deleteLikes(likes.getId());
        }

        newsDao.deleteNews(newsId);

        json.setResult(true);
        return json;
    }


    public static void putObject(String date, String filename, InputStream content,
                                 Long size) throws FileNotFoundException {

        // 初始化OSSClient
        OSSClient client = new OSSClient("W6PVM427mSEWlvEz",
                "h7NoXlxcjCqyeOWeuT43LungGmGRSd");

        // 获取指定文件的输入流
        // File file = new File(filePath);
        // InputStream content = new FileInputStream(file);

        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();

        // 必须设置ContentLength
        meta.setContentLength(size);

        // 上传Object.
        PutObjectResult result = client.putObject("icake", "news/" + date
                + "/" + filename, content, meta);

        // 打印ETag
        System.out.println(result.getETag());
    }
}
